from typing import Dict, List
from fastapi import WebSocket 

class ConnectionManager:
    def __init__(self):
        # 存储所有活动的WebSocket连接
        self.active_connections: Dict[str, WebSocket] = {} 

    async def connect_client(self, websocket: WebSocket,client_id:str):
        await websocket.accept() 
        print(f"成功连接：{client_id}")
        # 存储连接
        self.active_connections[client_id] = websocket  
        # 返回连接ID
        return client_id

    def disconnect_client(self, client_id: str):
        # 删除连接
        print(f"断开连接：{client_id}")
        if client_id in self.active_connections:
            del self.active_connections[client_id] 
 

    async def send_personal_message(self, message: dict, client_id: str):
        """发送个人消息到指定连接"""
        if client_id and client_id in self.active_connections:
            print(f"开始发送:{client_id}")
            try:  
              await self.active_connections[client_id].send_json(message) 
            except Exception as e:
                 print(f"发送错误:{client_id} {str(e)}")

    async def broadcast(self, message: dict):
        """广播消息到所有连接"""
        for connection in self.active_connections.values():
            await connection.send_json(message)

# 创建全局连接管理器实例
manager = ConnectionManager()